package com.example.common;

import com.google.common.collect.Maps;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.springframework.http.HttpStatus;

import java.io.Serializable;
import java.util.Map;

/**
 * @author zy
 * @version 1
 * @since 2021/01/28
 */
@Data
public class R<T> implements Serializable {

    @ApiModelProperty(value = "是否成功")
    private Boolean success;

    @ApiModelProperty(value = "返回码")
    private Integer code;

    @ApiModelProperty(value = "返回消息")
    private String message;

    @ApiModelProperty(value = "返回数据")
    private transient Map<String, T> data = Maps.newHashMap();


    private R() {
    }

    public static R result(boolean result) {
        R r = new R();
        r.setSuccess(result);
        r.setCode(result ? HttpStatus.OK.value() : HttpStatus.INTERNAL_SERVER_ERROR.value());
        r.setMessage(result ? HttpStatus.OK.getReasonPhrase() : HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase());
        return r;
    }

    public static R ok() {
        R r = new R();
        r.setSuccess(true);
        r.setCode(HttpStatus.OK.value());
        r.setMessage(HttpStatus.OK.getReasonPhrase());
        return r;
    }

    public static R ok(Integer code) {
        R r = new R();
        r.setSuccess(true);
        r.setCode(code);
        r.setMessage(HttpStatus.OK.getReasonPhrase());
        return r;
    }


    public static R ok(String message) {
        R r = new R();
        r.setSuccess(true);
        r.setCode(HttpStatus.OK.value());
        r.setMessage(message);
        return r;
    }


    public static R error() {
        R r = new R();
        r.setSuccess(false);
        r.setCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
        r.setMessage(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase());
        return r;
    }


    public static R error(Integer code, String message) {
        R r = new R();
        r.setSuccess(false);
        r.setCode(code);
        r.setMessage(message);
        return r;
    }

    public static R error(String message) {
        R r = new R();
        r.setSuccess(false);
        r.setCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
        r.setMessage(message);
        return r;
    }

    public R success(Boolean success) {
        this.setSuccess(success);
        return this;
    }

    public R message(String message) {
        this.setMessage(message);
        return this;
    }

    public R code(Integer code) {
        this.setCode(code);
        return this;
    }

    public R data(String key, T value) {
        this.data.put(key, value);
        return this;
    }


    public R data(T value) {
        this.data.put("data", value);
        return this;
    }

    public R data(Map<String, T> map) {
        this.setData(map);
        return this;
    }
}
